package com.hyper_yang.javase.supplement.tryCloneable;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

/*
clone (shallow) 被拷贝对象的引用属性，不会拷贝，不会独立开辟空间
    step1: class -> implement Cloneable
    step2: override clone() methods
    step3: another Bean to call this method

clone (deep) 被拷贝对象开辟新空间，被拷贝对象的引用属性也开辟新空间
    这里的引用属性也要去 implement Cloneable接口
    以 Person里拷贝 MyData引用属性为例:
  class Person:
        @Override
        protected Object clone() throws CloneNotSupportedException {
            // 1. 拷贝当前对象
            Object o = super.clone();
            Person copy = (Person) o;
            // 2. 拷贝当前对象的引用属性
            Object o2 = this.birthday.clone();
            MyData copy2 = (MyData) o2;
            // 3. 整合
            copy.birthday = copy2;
            return copy;
        }
 */
public class TestCloneable {

    @DisplayName("测试一: 实现Cloneable接口前")
    @Test
    public void test() {
        Student stu1 = new Student("张三", 13);
        System.out.println("stu1: " + stu1);
        Student stu2 = stu1;
        stu2.setName("吕布");
        System.out.println("stu2: " + stu2);
        System.out.println("stu1: " + stu1);
    }

    @DisplayName("测试二: 实现Cloneable接口后")
    @Test
    public void test2() throws CloneNotSupportedException {
        Student stu1 = new Student("张三", 13);
        System.out.println("stu1: " + stu1);
        if (stu1.clone() instanceof Student) {
            Student stu2 = (Student) stu1.clone();
            stu2.setName("吕布");
            System.out.println("stu2: " + stu2);
        }
        System.out.println("stu1: " + stu1);
    }
}
